'''
https://leetcode.cn/problems/maximum-width-of-binary-tree/description/
'''
from collections import deque
from typing import Optional

from c06_tree.utils import TreeNode


class Solution:
    def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
        if not root: return 0
        q = deque([(root, 0)])
        res = 1
        while q:
            level_size = len(q)
            l, r = float('inf'), -1
            for i in range(level_size):
                cur, idx = q.popleft()
                l = min(l, idx)
                r = max(r, idx)
                if cur.left:
                    q.append((cur.left, idx * 2 + 1))
                if cur.right:
                    q.append((cur.right, idx * 2 + 2))
            res = max(res, r - l + 1)
        return res
